import requests
import time
import json
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
# 使用简单的User-Agent替代fake_useragent避免打包问题
try:
    from simple_useragent import UserAgent
except ImportError:
    # 如果simple_useragent不可用，使用内置的简单实现
    class UserAgent:
        def __init__(self):
            self.agents = [
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0',
            ]

        @property
        def random(self):
            import random
            return random.choice(self.agents)

from config import Config
from professional_captcha_solver import ProfessionalCaptchaSolver

class Register4399Bot:
    def __init__(self, config=None):
        self.config = config if config else Config()
        self.captcha_solver = ProfessionalCaptchaSolver()
        self.session = requests.Session()
        self.driver = None
        self.success_count = 0
        self.failed_count = 0
        # 动态身份信息（每次使用时设置）
        self.real_name = None
        self.id_card = None
        
        # 设置User-Agent
        ua = UserAgent()
        self.session.headers.update({
            'User-Agent': ua.random,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding': 'gzip, deflate',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
        })

    def set_identity_info(self, real_name, id_card):
        """设置身份信息（动态设置，不保存）"""
        self.real_name = real_name
        self.id_card = id_card
        print(f"✅ 已设置身份信息: {real_name} - {id_card}")

    def setup_driver(self):
        """设置Chrome浏览器"""
        try:
            import os
            chrome_options = Options()

            # 防御性编程：确保config和BROWSER_CONFIG存在
            if not self.config:
                print("⚠️ 配置对象为空，使用默认配置")
                from config import Config
                self.config = Config()

            if not hasattr(self.config, 'BROWSER_CONFIG') or not self.config.BROWSER_CONFIG:
                print("⚠️ 浏览器配置为空，使用默认配置")
                self.config.BROWSER_CONFIG = {'headless': False, 'window_size': (1200, 800)}

            if self.config.BROWSER_CONFIG.get('headless', False):
                chrome_options.add_argument('--headless')

            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--disable-dev-shm-usage')
            chrome_options.add_argument('--disable-blink-features=AutomationControlled')
            chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
            chrome_options.add_experimental_option('useAutomationExtension', False)

            # 指定Chrome浏览器路径
            chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
            if os.path.exists(chrome_path):
                chrome_options.binary_location = chrome_path

            # 设置窗口大小
            window_size = self.config.BROWSER_CONFIG.get('window_size', (1200, 800))
            width, height = window_size
            chrome_options.add_argument(f'--window-size={width},{height}')

            # 创建WebDriver - 优先使用本地chromedriver
            driver_created = False

            # 方式1: 尝试使用本地chromedriver
            try:
                local_chromedriver = r".\chromedriver.exe"
                if os.path.exists(local_chromedriver):
                    print(f"使用本地chromedriver: {local_chromedriver}")
                    service = Service(local_chromedriver)
                    self.driver = webdriver.Chrome(service=service, options=chrome_options)
                    driver_created = True
                    print("✅ 使用本地chromedriver成功")
            except Exception as e:
                print(f"本地chromedriver失败: {e}")

            # 方式2: 尝试使用ChromeDriverManager
            if not driver_created:
                try:
                    chromedriver_path = ChromeDriverManager().install()
                    service = Service(chromedriver_path)
                    self.driver = webdriver.Chrome(service=service, options=chrome_options)
                    driver_created = True
                    print("✅ 使用ChromeDriverManager成功")
                except Exception as e:
                    print(f"ChromeDriverManager失败: {e}")

            # 方式3: 尝试使用已知路径
            if not driver_created:
                try:
                    possible_paths = [
                        r'C:\Users\Zz185\.wdm\drivers\chromedriver\win64\138.0.7204.94\chromedriver-win32\chromedriver.exe',
                        r"chromedriver.exe",
                        r"C:\chromedriver\chromedriver.exe"
                    ]

                    for path in possible_paths:
                        if os.path.exists(path):
                            print(f"找到chromedriver: {path}")
                            service = Service(path)
                            self.driver = webdriver.Chrome(service=service, options=chrome_options)
                            driver_created = True
                            print(f"✅ 使用备用路径成功: {path}")
                            break

                    if not driver_created:
                        raise Exception("找不到兼容的chromedriver")
                except Exception as e:
                    print(f"备用WebDriver创建失败: {e}")
                    raise e

            # 执行反检测脚本
            self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

            return True
        except Exception as e:
            print(f"浏览器设置失败: {e}")
            return False
    
    def force_refresh_and_navigate(self, url, description="页面"):
        """强制刷新并导航到指定页面"""
        try:
            print(f"🔄 强制刷新并导航到{description}...")

            # 方法1: JavaScript强制刷新
            try:
                self.driver.execute_script("location.reload(true);")
                time.sleep(0.1)  # 极速刷新
            except:
                pass

            # 方法2: 清除缓存和Cookie
            try:
                self.driver.delete_all_cookies()
                time.sleep(0.05)  # 极速清理
            except:
                pass

            # 方法3: 重新导航
            self.driver.get(url)
            time.sleep(0.2)  # 极速导航

            # 方法4: 再次刷新确保页面完全加载
            self.driver.refresh()
            time.sleep(0.1)  # 极速刷新

            # 方法5: 检查页面是否正确加载
            current_url = self.driver.current_url
            print(f"📍 当前页面: {current_url}")

            if "register" in url and "register" in current_url.lower():
                print(f"✅ 成功导航到{description}")
                return True
            elif "register" not in url:
                print(f"✅ 成功导航到{description}")
                return True
            else:
                print(f"⚠️ 页面可能未正确加载，但继续尝试")
                return True

        except Exception as e:
            print(f"❌ 强制刷新和导航失败: {e}")
            return False

    def close_driver(self):
        """关闭浏览器"""
        if self.driver:
            self.driver.quit()
            self.driver = None
    
    def wait_for_element(self, by, value, timeout=10):
        """等待元素出现"""
        try:
            element = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located((by, value))
            )
            return element
        except Exception as e:
            print(f"等待元素失败 {value}: {e}")
            return None
    
    def check_captcha_exists(self):
        """检查是否存在验证码"""
        try:
            captcha_img = self.driver.find_elements(By.XPATH, "//img[contains(@src, 'captcha')]")
            return len(captcha_img) > 0
        except:
            return False

    def refresh_captcha(self):
        """自动刷新验证码"""
        try:
            print("🔄 正在自动刷新验证码...")

            # 方法1: 点击验证码图片刷新
            try:
                captcha_img = self.driver.find_element(By.ID, "captcha")
                if captcha_img:
                    captcha_img.click()
                    print("✅ 已点击验证码图片刷新")
                    time.sleep(0.1)
                    return True
            except Exception as e:
                print(f"点击验证码图片失败: {e}")

            # 方法2: 查找刷新按钮
            try:
                refresh_selectors = [
                    "//a[contains(@onclick, 'captcha')]",
                    "//span[contains(@onclick, 'captcha')]",
                    "//img[contains(@onclick, 'captcha')]",
                    "//*[contains(text(), '刷新')]",
                    "//*[contains(text(), '换一张')]"
                ]

                for selector in refresh_selectors:
                    try:
                        refresh_btn = self.driver.find_element(By.XPATH, selector)
                        if refresh_btn and refresh_btn.is_displayed():
                            refresh_btn.click()
                            print("✅ 已点击刷新按钮")
                            time.sleep(0.1)
                            return True
                    except:
                        continue
            except Exception as e:
                print(f"查找刷新按钮失败: {e}")

            # 方法3: 执行JavaScript刷新验证码
            try:
                js_refresh_commands = [
                    "if(typeof refreshCaptcha === 'function') refreshCaptcha();",
                    "if(typeof changeCaptcha === 'function') changeCaptcha();",
                    "if(typeof reloadCaptcha === 'function') reloadCaptcha();",
                    "document.getElementById('captcha').src = document.getElementById('captcha').src + '?' + Math.random();"
                ]

                for cmd in js_refresh_commands:
                    try:
                        self.driver.execute_script(cmd)
                        print("✅ 已执行JavaScript刷新验证码")
                        time.sleep(0.1)
                        return True
                    except:
                        continue
            except Exception as e:
                print(f"JavaScript刷新失败: {e}")

            # 方法4: 刷新整个页面（最后手段）
            print("🔄 使用页面刷新作为最后手段...")
            self.driver.refresh()
            time.sleep(0.3)
            return True

        except Exception as e:
            print(f"❌ 刷新验证码失败: {e}")
            return False

    def solve_captcha(self):
        """解决验证码 - 仅使用自动识别，失败时返回None触发刷新"""
        try:
            # 查找验证码图片元素
            captcha_img = self.driver.find_element(By.ID, "captcha")

            # 直接截取验证码图片区域
            print("📸 正在截取验证码图片...")
            captcha_screenshot = captcha_img.screenshot_as_png

            # 保存截取的验证码图片
            with open('current_captcha.png', 'wb') as f:
                f.write(captcha_screenshot)

            # 仅使用自动识别验证码
            print("🤖 正在自动识别验证码...")
            captcha_code = self.captcha_solver.recognize_captcha(captcha_screenshot)

            if captcha_code:
                print(f"✅ 验证码识别成功: {captcha_code}")
                return captcha_code
            else:
                print("❌ 自动识别失败，将触发验证码刷新")
                return None

        except Exception as e:
            print(f"❌ 验证码处理失败: {e}")
            return None

    def check_agreement(self):
        """勾选用户协议"""
        try:
            print("勾选用户协议...")

            # 查找协议复选框，尝试多种定位方式
            agreement_checkbox = None

            # 方式1：通过包含"同意"文本的复选框
            try:
                agreement_checkbox = self.driver.find_element(By.XPATH, "//input[@type='checkbox' and contains(@name, 'agree')]")
            except:
                try:
                    # 方式2：通过ID定位
                    agreement_checkbox = self.driver.find_element(By.XPATH, "//input[@type='checkbox'][contains(following-sibling::text(), '同意') or contains(following-sibling::label, '同意')]")
                except:
                    try:
                        # 方式3：查找所有复选框，选择第一个
                        checkboxes = self.driver.find_elements(By.XPATH, "//input[@type='checkbox']")
                        if checkboxes:
                            agreement_checkbox = checkboxes[0]
                    except:
                        pass

            if agreement_checkbox:
                # 检查是否已经勾选
                if not agreement_checkbox.is_selected():
                    agreement_checkbox.click()
                    time.sleep(0.1)
                    print("✅ 已勾选用户协议")
                else:
                    print("✅ 用户协议已经勾选")
                return True
            else:
                print("❌ 找不到用户协议复选框")
                return False

        except Exception as e:
            print(f"勾选用户协议失败: {e}")
            return False

    def fill_registration_form(self, username, password, real_name, id_card, qq=None):
        """填写注册表单"""
        try:
            # 无延迟，立即开始填写

            print("开始填写注册表单...")

            # 填写用户名 - 使用正确的ID定位
            print("填写用户名...")
            username_input = self.wait_for_element(By.ID, "j-username")
            if username_input:
                # 清空预填充的用户名
                username_input.clear()
                username_input.send_keys(username)
                print(f"用户名已填写: {username}")
            else:
                print("❌ 找不到用户名输入框")
                return False

            # 填写密码
            print("填写密码...")
            password_input = self.wait_for_element(By.ID, "j-password")
            if password_input:
                password_input.clear()
                password_input.send_keys(password)
                print("密码已填写")
            else:
                print("❌ 找不到密码输入框")
                return False

            # 确认密码
            print("填写确认密码...")
            confirm_password_input = self.wait_for_element(By.ID, "j-passwordveri")
            if confirm_password_input:
                confirm_password_input.clear()
                confirm_password_input.send_keys(password)
                print("确认密码已填写")
            else:
                print("❌ 找不到确认密码输入框")
                return False

            # 填写真实姓名
            print("填写真实姓名...")
            real_name_input = self.wait_for_element(By.ID, "j-realname")
            if real_name_input:
                real_name_input.clear()
                real_name_input.send_keys(real_name)
                print(f"真实姓名已填写: {real_name}")
            else:
                print("❌ 找不到真实姓名输入框")
                return False

            # 填写身份证号
            print("填写身份证号...")
            id_card_input = self.wait_for_element(By.ID, "j-idcard")
            if id_card_input:
                id_card_input.clear()
                id_card_input.send_keys(id_card)
                print(f"身份证号已填写: {id_card}")
            else:
                print("❌ 找不到身份证输入框")
                return False

            print("✅ 表单填写完成")
            return True

        except Exception as e:
            print(f"填写表单失败: {e}")
            return False

    def submit_registration(self):
        """提交注册表单"""
        try:
            print("提交注册表单...")

            # 查找并点击注册按钮 - 使用更精确的定位
            submit_button = None

            # 尝试多种方式定位提交按钮
            try:
                submit_button = self.driver.find_element(By.CLASS_NAME, "ptlogin_register")
            except:
                try:
                    submit_button = self.driver.find_element(By.XPATH, "//input[@type='submit']")
                except:
                    try:
                        submit_button = self.driver.find_element(By.XPATH, "//button[contains(@class, 'register') or contains(text(), '注册')]")
                    except:
                        pass

            if not submit_button:
                return False, "找不到注册按钮"

            # 点击注册按钮
            submit_button.click()
            print("已点击注册按钮，等待结果...")

            # 极速等待结果
            time.sleep(0.1)  # 最小延迟

            # 检查是否注册成功
            page_source = self.driver.page_source
            current_url = self.driver.current_url

            print(f"当前URL: {current_url}")

            # 根据页面内容判断注册结果
            if "注册成功" in page_source or "欢迎" in page_source or "success" in current_url.lower():
                return True, "注册成功"
            elif "用户名已存在" in page_source or "用户名重复" in page_source:
                return False, "用户名已存在"
            elif "验证码错误" in page_source or "验证码不正确" in page_source:
                return False, "验证码错误"
            elif "身份证" in page_source and "错误" in page_source:
                return False, "身份证信息错误"
            elif "真实姓名" in page_source and "错误" in page_source:
                return False, "真实姓名格式错误"
            else:
                # 保存页面源码用于调试
                with open('register_result.html', 'w', encoding='utf-8') as f:
                    f.write(page_source)
                print("注册结果页面已保存到 register_result.html")
                return False, "未知错误，请查看 register_result.html"

        except Exception as e:
            print(f"提交注册失败: {e}")
            return False, str(e)

    def register_single_account(self, username_prefix="dai", uuid_length=10):
        """注册单个账号

        Args:
            username_prefix: 账号名前缀，默认"dai"
            uuid_length: UUID随机数位数，默认10位
        """
        # 防御性编程：确保所有必要的对象都存在
        if not self.config:
            print("❌ 配置对象为空")
            return None, None

        if not self.driver:
            print("❌ 浏览器驱动为空，请先调用setup_driver()")
            return None, None

        username = self.config.generate_username(username_prefix, uuid_length)
        password = self.config.DEFAULT_PASSWORD
        real_name = self.real_name  # 使用动态设置的身份信息
        id_card = self.id_card      # 使用动态设置的身份信息
        qq = self.config.generate_qq()

        if not real_name or not id_card:
            print("❌ 缺少身份信息，无法注册")
            return None, None

        print(f"开始注册账号: {username}")
        print(f"使用身份信息: {real_name} - {id_card}")

        retry_count = 0
        max_retry = getattr(self.config, 'MAX_RETRY', 3)  # 防御性获取重试次数
        while retry_count < max_retry:
            try:
                # 打开注册页面
                self.driver.get(self.config.REGISTER_URL)
                time.sleep(0.1)  # 极速页面加载

                # 填写注册表单
                if not self.fill_registration_form(username, password, real_name, id_card, qq):
                    retry_count += 1
                    continue

                # 检查是否需要验证码
                if self.check_captcha_exists():
                    print("检测到验证码，正在处理...")

                    # 验证码自动刷新重试机制
                    captcha_retry = 0
                    captcha_success = False
                    max_captcha_attempts = 10  # 最多尝试10次自动刷新

                    while captcha_retry < max_captcha_attempts and not captcha_success:
                        captcha_code = self.solve_captcha()

                        if not captcha_code:
                            print(f"🔄 验证码识别失败，自动刷新验证码 (尝试 {captcha_retry + 1}/{max_captcha_attempts})")
                            self.refresh_captcha()
                            captcha_retry += 1
                            continue

                        # 填写验证码 - 使用正确的ID定位
                        print(f"🔍 填写验证码 (尝试 {captcha_retry + 1}/{max_captcha_attempts}): {captcha_code}")
                        captcha_input = self.wait_for_element(By.ID, "inputCaptcha")
                        if captcha_input:
                            captcha_input.clear()
                            captcha_input.send_keys(captcha_code)
                            captcha_success = True
                            print(f"✅ 验证码已填写: {captcha_code}")
                        else:
                            print("❌ 找不到验证码输入框，刷新验证码重试")
                            self.refresh_captcha()
                            captcha_retry += 1

                    if not captcha_success:
                        print(f"❌ 验证码处理失败，已尝试 {max_captcha_attempts} 次自动刷新，跳过此次注册")
                        retry_count += 1
                        continue

                # 勾选"我同意"按钮
                if not self.check_agreement():
                    print("勾选协议失败，跳过此次注册")
                    retry_count += 1
                    continue

                # 提交注册
                success, message = self.submit_registration()

                if success:
                    self.success_count += 1
                    print(f"✓ 账号 {username} 注册成功！")

                    # 立即保存成功的账号信息到accounts.txt（仅保存用户名和密码）
                    self.save_account_to_txt(username, password)

                    print("💾 账号信息已保存到 accounts.txt")
                    print("🎉 账号注册成功！准备关闭浏览器...")

                    return username, password
                else:
                    print(f"✗ 账号 {username} 注册失败: {message}")

                    if "用户名已存在" in message:
                        # 用户名冲突，生成新用户名重试
                        username = self.config.generate_username()
                        print(f"用户名冲突，生成新用户名: {username}")
                    elif "验证码错误" in message:
                        # 验证码错误，自动刷新验证码重试
                        print("🔄 验证码错误，自动刷新验证码...")
                        self.refresh_captcha()
                        time.sleep(0.1)  # 极速等待页面刷新

                    retry_count += 1

            except Exception as e:
                print(f"注册过程出错: {e}")
                retry_count += 1
                time.sleep(0.1)

        self.failed_count += 1
        print(f"✗ 账号 {username} 注册失败，已达到最大重试次数")
        return None, None



    def save_account_to_txt(self, username, password):
        """立即保存账号信息到accounts.txt文件 - 只保存用户名和密码"""
        try:
            import sys
            import os

            # 获取exe所在目录，确保accounts.txt在exe同目录下
            if hasattr(sys, '_MEIPASS'):
                exe_dir = os.path.dirname(sys.executable)
            else:
                exe_dir = os.path.dirname(os.path.abspath(__file__))

            accounts_file = os.path.join(exe_dir, 'accounts.txt')
            print(f"📁 保存账号到: {accounts_file}")

            with open(accounts_file, 'a', encoding='utf-8') as f:
                # 只保存用户名和密码
                f.write(f"{username}\t{password}\n")
            print(f"✅ 账号信息已立即保存到 accounts.txt: {username}")
        except Exception as e:
            print(f"❌ 保存到accounts.txt失败: {e}")

    def batch_register(self, count):
        """批量注册账号 - 每个账号使用独立的浏览器会话"""
        print(f"开始批量注册 {count} 个账号...")
        if self.real_name and self.id_card:
            print(f"使用身份信息: {self.real_name} - {self.id_card}")
        else:
            print("❌ 缺少身份信息，无法进行批量注册")
            return
        print("🔄 采用每账号独立浏览器会话策略，避免iframe和状态问题")

        for i in range(count):
            print(f"\n{'='*60}")
            print(f"🎯 注册进度: {i+1}/{count}")
            print(f"{'='*60}")

            try:
                # 为每个账号初始化新的浏览器会话
                print(f"🚀 为第 {i+1} 个账号初始化新的浏览器会话...")

                if not self.setup_driver():
                    print("❌ 浏览器初始化失败，跳过此账号")
                    self.failed_count += 1
                    continue

                print("✅ 浏览器初始化成功")

                # 注册单个账号
                success = self.register_single_account()

                # 无论成功失败，立即关闭浏览器
                print("🔄 立即关闭浏览器会话...")
                self.close_driver()
                print("✅ 浏览器会话已关闭")

                if success:
                    print(f"🎉 第 {i+1} 个账号注册成功并已保存！")
                else:
                    print(f"❌ 第 {i+1} 个账号注册失败")

                # 移除账号间隔等待，立即进行下一个账号
                if i < count - 1:
                    print("🚀 立即进行下一个账号注册...")

            except Exception as e:
                print(f"❌ 处理第 {i+1} 个账号时出错: {e}")
                self.failed_count += 1

                # 确保浏览器被关闭
                try:
                    self.close_driver()
                except:
                    pass

                # 立即继续下一个账号
                if i < count - 1:
                    print("🚀 立即继续下一个账号...")

        print(f"\n=== 批量注册完成 ===")
        print(f"成功注册: {self.success_count} 个")
        print(f"注册失败: {self.failed_count} 个")
        print(f"成功率: {self.success_count/(self.success_count+self.failed_count)*100:.1f}%")

        # 询问是否进行一条龙服务（登录投票）
        if self.success_count > 0:
            return self.ask_for_login_and_vote()
        else:
            print("账号信息已保存到 accounts.txt")

    def ask_for_login_and_vote(self):
        """询问是否进行登录投票一条龙服务"""
        try:
            print(f"\n{'='*60}")
            print("🎉 注册完成！是否继续一条龙服务？")
            print(f"{'='*60}")
            print(f"✅ 成功注册了 {self.success_count} 个账号")
            print("💡 可以立即使用这些账号进行登录投票")
            print()

            choice = input("是否立即进行登录投票？(y/n): ").strip().lower()

            if choice == 'y':
                return self.start_login_and_vote_service()
            else:
                print("✅ 注册完成，账号已保存到 accounts.txt")
                print("💡 您可以稍后通过主菜单选择投票功能")
                return True

        except Exception as e:
            print(f"❌ 询问一条龙服务时出错: {e}")
            return True

    def start_login_and_vote_service(self):
        """开始登录投票一条龙服务"""
        try:
            print(f"\n{'='*60}")
            print("🚀 开始登录投票一条龙服务")
            print(f"{'='*60}")

            # 让用户选择投票选项
            print("请选择投票选项:")
            print("1. 深海女神")
            print("2. 沧澜春华")
            print("3. 沧澜战姬")

            while True:
                try:
                    choice = input("请输入选项编号 (1-3): ").strip()
                    vote_option = int(choice)
                    if 1 <= vote_option <= 3:
                        break
                    else:
                        print("请输入1-3之间的数字")
                except ValueError:
                    print("请输入有效的数字")

            option_names = {1: "深海女神", 2: "沧澜春华", 3: "沧澜战姬"}
            print(f"您选择了: {option_names[vote_option]}")

            confirm = input("确认开始批量登录投票吗？(y/n): ").strip().lower()
            if confirm != 'y':
                print("已取消一条龙服务")
                return True

            # 导入投票机器人并开始投票
            from vote_bot import VoteBot

            print(f"\n🔄 正在启动投票机器人...")
            vote_bot = VoteBot()

            # 运行投票活动
            vote_bot.run_vote_campaign(vote_option)

            print(f"\n🎉 一条龙服务完成！")
            print("✅ 注册 → 登录 → 投票 全部完成")

            return True

        except Exception as e:
            print(f"❌ 一条龙服务出错: {e}")
            return False

def main():
    """主函数"""
    try:
        # 创建注册机器人实例
        bot = Register4399Bot()

        # 注册单个账号进行测试
        print("开始测试注册...")
        bot.setup_driver()
        success = bot.register_single_account()
        bot.close_driver()

        if success:
            print("✅ 测试注册成功！")
        else:
            print("❌ 测试注册失败")

    except KeyboardInterrupt:
        print("\n用户中断程序")
    except Exception as e:
        print(f"程序运行出错: {e}")

if __name__ == "__main__":
    main()
